package org.yxing.palpalgps.activity;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.yxing.palpalgps.BaseActivity;
import org.yxing.palpalgps.PalPalGPSApplication;
import org.yxing.palpalgps.R;
import org.yxing.palpalgps.domain.UserInfo;
import org.yxing.palpalgps.http.AsyncRequest;
import org.yxing.palpalgps.services.XMPPService;
import org.yxing.palpalgps.utils.ConfigHelper;
import org.yxing.palpalgps.utils.Helper;
import org.yxing.palpalgps.utils.Utils;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

/**
 * 登陆到
 * @author yuxing
 */
public class LoginActivity extends BaseActivity {
	private static final String TAG = "LoginActivity";
	public static String FINENAME = "facebook_sso_data";
	public static final int AUTH_ACTIVITY_CODE = 2;
	private static final String FACEBOOK_APPID = "184934008240981";
	
	Facebook mFacebook;
	
	private SharedPreferences mPrefs;
	
	/**
	 * 当前用户对象
	 */
	private UserInfo mCurrentUser;
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        
        mCurrentUser = ConfigHelper.getNowUser();
        
        //create facebook instance
        mFacebook = new Facebook(FACEBOOK_APPID);
        
        mPrefs = getSharedPreferences(FINENAME, MODE_PRIVATE);
        String token = mPrefs.getString(UserInfo.KEY_TOKEN, null);
        long expires = mPrefs.getLong(UserInfo.KEY_EXPIRES, 0);
        if (token != null)
            mFacebook.setAccessToken(token);
        if (expires != 0)
            mFacebook.setAccessExpires(expires);
        
        if (mFacebook.isSessionValid()) {
            finishLoginFacebook();
        }
        
        findViewById(R.id.loginButton).setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                loginWithFacebook();
            }
        });
    }
    
    private void loginWithFacebook() {
        mFacebook.authorize(this, new String[]{}, AUTH_ACTIVITY_CODE, new LoginDialogListener());
    }
    
    private final class LoginDialogListener implements DialogListener {
        public void onComplete(Bundle values) {
            Log.d(TAG, "complete");
            SharedPreferences.Editor edit = mPrefs.edit();
            edit.putString(UserInfo.KEY_TOKEN, mFacebook.getAccessToken());
            edit.putLong(UserInfo.KEY_EXPIRES, mFacebook.getAccessExpires());
            edit.commit();
            finishLoginFacebook();
        }
        
        public void onFacebookError(FacebookError e) {
            Log.e("facebook", e.getMessage());
            displayToast(e.getMessage());
        }
        
        public void onError(DialogError e) {
            Log.e("facebook", e.getMessage());
            displayToast(e.getMessage());
        }
        
        public void onCancel() {
            Log.v("facebook", "onCancel");
        }
    }
    
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (resultCode == RESULT_OK) {
            if (requestCode == 0) {
            	stopServices();
            	boolean isExit = true;
            	
                if (data != null) {
                    boolean isLogout = data.getBooleanExtra("logout", false);
                    if (isLogout) {
                        logout();
                        isExit = false;
                    }
                }
                
                if (isExit) {
                	finish();
                    Helper.exit(true);
                }
                
            } else if (requestCode == AUTH_ACTIVITY_CODE) {
                mFacebook.authorizeCallback(requestCode, resultCode, data);
            }
        }
    }
    
    /**
     * facebook 验证成功后调用
     */
    private void finishLoginFacebook() {
        mCurrentUser.setToken(mFacebook.getAccessToken());
        loginToPalPalServer(mCurrentUser);
    }
    
    /**
     * 登录到PalPalGPS服务器
     */
    private void loginToPalPalServer(final UserInfo user) {
    	
    	String deviceId = android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);;
    	
    	final ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    	params.add(new BasicNameValuePair("token", user.getToken()));
    	params.add(new BasicNameValuePair("device_id", deviceId));
    	params.add(new BasicNameValuePair("device_type", "android"));
    	
    	String time = Utils.time();
    	params.add(new BasicNameValuePair("time", time));
    	params.add(new BasicNameValuePair("sig", Helper.getSig(deviceId, time)));
    	
    	AsyncRequest ar = new AsyncRequest(this);
    	ar.fetch("user/register", params, new AsyncRequest.FetchListener() {
            
            public void onComplete(JSONObject response) {
                try {
                    user.setId(response.getString("uid"));
                    user.setSession(response.getString("session"));
                    user.setChatPassword(response.getString(UserInfo.KEY_CHAT_PASSWORD));
                    user.setFace(response.getString("picture"));
                    goHome();
                } catch (JSONException e) {
                    Log.w(TAG, e.getMessage());
                }
            }
            
            public void onError(int code, String msg) {
                
            }
        });
    }
    
    /**
     * redirect home
     */
    private void goHome() {
        PalPalGPSApplication application = (PalPalGPSApplication) getApplication();
        application.setUser(mCurrentUser);
        
		Intent intent = new Intent();
		intent.setClass(this, HomeActivity.class);
		startActivityForResult(intent, 0);
    }
    
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            Helper.exit(true);
        }
        return super.onKeyUp(keyCode, event);
    }
    
    public void logout() {
//        SharedPreferences.Editor edit = mPrefs.edit();
//        edit.clear();
//        edit.commit();
//        try {
//            mFacebook.logout(this);
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    	
    	new LogoutAsyncTask().execute();
    }
    
    private class LogoutAsyncTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... paramArrayOfParams) {
	        SharedPreferences.Editor edit = mPrefs.edit();
	        edit.clear();
	        edit.commit();
	        try {
	            mFacebook.logout(LoginActivity.this);
	        } catch (MalformedURLException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
			
			return null;
		}
    	
    }
    
    /**
     * stop services
     */
    private void stopServices() {
        stopService(new Intent(this, XMPPService.class));
    }
}
